<template>
  <div class="app-container">
    <div class="block">文章标题</div>
    <el-input v-model="form.title" placeholder="请输入文章标题"></el-input>

    <div class="block">文章编辑</div>
    <Editor ref="toastuiEditor" :initiaValue="form.editorText" />

    <div class="block">文章描述</div>
    <el-input
      type="textarea"
      :rows="8"
      placeholder="请输入内容"
      v-model="form.description"
    >
    </el-input>

    <div class="block">文章头图</div>
    <Upload uploadTitle="文章头图" v-model="form.thumb" />

    <div class="block">选择分类</div>
    <el-select v-model="form.select" placeholder="请选择文章分类">
      <el-option
        v-for="item in blogType"
        :key="item.id"
        :label="item.name"
        :value="item.id"
      ></el-option>
    </el-select>
    <div>
      <el-button clasq s="onSubmit" type="primary" @click="addArticleHandle"
        >提交</el-button
      >
    </div>
  </div>
</template>

<script>
import { getBlogType } from "@/api/blogType";
import { Editor } from "@toast-ui/vue-editor";
import { addBlog } from "@/api/blog";
import "@toast-ui/editor/dist/toastui-editor.css";
import "@toast-ui/editor/dist/i18n/zh-cn";
import Upload from "@/components/Upload.vue";
export default {
  created() {
    getBlogType().then(({ data }) => {
      this.blogType = data;
    });
  },
  data() {
    return {
      form: {
        title: "", // 文章标题
        editorText: "", // 文章内容
        description: "", // 文章描述
        thumb: "", // 文章头图
        select: "", // 选择分类
      },
      imageUrl: "", // 上传图片的地址
      blogType: [],
      isSelect: "true",
    };
  },
  components: {
    Editor,
    Upload,
  },
  methods: {
    addArticleHandle() {
      //创建obj 对象 存储数据
      let obj = {
        title: this.form.title,
        description: this.form.description,
        createDate: new Date().getTime(),
        categoryId: this.form.select,
        // toc 传递一个空数组过去，之后在服务器根据 markdown 的内容来生成 toc 目录
        toc: [],
        thumb: this.form.thumb,
        // 获取editor的内容
        htmlContent: this.$refs.toastuiEditor.invoke("getHTML"),
        markdownContent: this.$refs.toastuiEditor.invoke("getMarkdown"),
      };

      // 1.判断是否为空
      let newObj = Object.keys(obj);
      let newObj1 = newObj.splice(5, 1);
      this.isSelect = true;
      newObj = newObj.reduce((pre, cur) => {
        if (obj[cur]) {
          pre[cur] = obj[cur];
        } else {
          this.isSelect = false;
          this.$message({
            message: `请填写完整 ${cur}`,
            type: "warning",
          });
        }
        return pre;
      }, {});

      if (this.isSelect) {
        addBlog(obj).then(() => {
          this.$message.success("添加成功");
          this.$router.push("/blogList");
        });
      }
    },
  },
};
</script>

<style>
.block {
  font-size: 16px;
  margin: 15px 0;
  font-weight: 100;
}
.onSubmit {
  margin-top: 20px;
}
</style>